package com.guli.msmService.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.guli.msmService.service.MsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author zxc
 * @date 2023/04/12 20:17
 **/
@Service
public class MsmServiceImpl implements MsmService {
    // 借助阿里云短信发送服务，发送验证码给指定手机号
    public boolean sendMsm(String phoneNumber, Map<String, String> map) {
        // 1.所要发送验证码的手机号为空的情况 ：
        if(StringUtils.isEmpty(phoneNumber)) return false;
        // 2.获取阿里云的访问权限 && 创建client对象 :
        DefaultProfile profile =
                DefaultProfile.getProfile("default",
                        "LTAI5tGoduzd9bgBczsfeL6K", "Bggqknbss9p7o5lUE6sEvVZc3ZuwoL");
        IAcsClient client = new DefaultAcsClient(profile);

        // 3.设置所要发送请求request的部分参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 4.设置所要发送请求的详细信息 ：
        request.putQueryParameter("PhoneNumbers", phoneNumber); // 所要发送的手机号
        request.putQueryParameter("SignName", "在线课程信息管理网站");// 所使用的签名
        request.putQueryParameter("TemplateCode", "SMS_276415185"); // 所使用的模板
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map)); // 所要发送的验证码信息

        try {
            // 5.发送request，获取到response;
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            boolean isSuccess = response.getHttpResponse().isSuccess();
            return isSuccess;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
